<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace App\Controller\Admin;

use App\Constants\ErrorCode;
use App\Constants\ServerList;
use App\Middleware\AdminMiddleware;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\GetMapping;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\PostMapping;

#[Controller(prefix: '/admin/Index'), Middleware(AdminMiddleware::class)]
class IndexController extends BaseController {

    #[PostMapping(path: 'upload')]
    public function upload(): array {
        $documentRoot = BASE_PATH . '/public';
        if ($this->request->hasFile('file')) {
            $fileObj = $this->request->file('file');
            if ($fileObj->isValid()) {
                $path = $documentRoot . '/upload/' . date('Ymd') . '/';
                if (!file_exists($path)) {
                    mkdir($path, 0755, true);
                }
                $new_name = md5(time() . uniqid('', true)) . '.' . $fileObj->getExtension();
                $fileObj->moveTo($path . $new_name);

                if ($fileObj->isMoved()) {
                    $host = str_replace($this->request->getPathInfo(), '', $this->request->url());
                    $basePath = str_replace($documentRoot, '', $path);

                    return $this->buildSuccess([
                        'fileName' => $new_name,
                        'fileUrl'  => $host . $basePath . $new_name
                    ]);
                }

                return $this->buildFailed(ErrorCode::FILE_SAVE_ERROR, '文件上传失败');
            }

            $error_message = match ($fileObj->getError()) {
                1 => '您上传的文件超过了PHP.INI配置文件中UPLOAD_MAX-FILESIZE的大小',
                2 => '您上传的文件超过了PHP.INI配置文件中的post_max_size的大小',
                3 => '文件只被部分上传',
                4 => '文件不能为空',
                default => '未知错误'
            };

            return $this->buildFailed(ErrorCode::FILE_SAVE_ERROR, $error_message);
        }

        return $this->buildFailed(ErrorCode::NOT_EXISTS, '未检测到文件');
    }

    /**
     * 获取服务器列表
     * @return array
     */
    #[GetMapping(path: 'serverList')]
    public function serverList(): array {
        return $this->buildSuccess(ServerList::YZTT_LIST_SHOW);
    }

}
